// pages/material/pages/basis/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        modify: false, //判断是否是修改
        on_index: '', //当前修改的索引
        //委托人资料
        full_name: '', //姓名
        phone_number: '', //电话
        idCard_z: '', //身份证（正）
        idCard_f: '', //身份证（反）
        idCard: '', //身份证号
        household: '', //户口本
    },
    set_input: function (e) {},
    //图片选择
    choose_images: function (e) {
        var that = this;
        let source = e.currentTarget.dataset.source; //当前占位图名字
        let type = e.currentTarget.dataset.type; // 类型（单图/多图）
        if (type == 0) { //单图
            wx.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: res => {
                    const src = res.tempFilePaths
                    var upload_img = source
                    that.setData({
                        [upload_img]: src
                    });
                }
            });
        } else if (type == 1) { //多图
            var in_source = source + '_files'; //当前占位图名字
            let in_count = source + '_max_vir'; //当前占位图名字
            let num_vir = e.currentTarget.dataset.num_vir; //限制数值
            wx.chooseImage({
                count: num_vir,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: res => {
                    const src = res.tempFilePaths;
                    console.log(src)
                    that.setData({
                        [in_count]: num_vir + 1,
                        [in_source]: that.data[in_source].concat(src)
                    });
                }
            });
        }
    },
    //删除图片
    to_delete: function (e) {
        console.log(e)
        var that = this;
        var select_type = e.currentTarget.dataset.source; //当前占位图名字
        that.setData({
            [select_type]: '',
        });
    },
    //查看图片
    previewImage: function (e) {
        var source = e.currentTarget.dataset.source;
        wx.previewImage({
            current: e.currentTarget.source, // 当前显示图片的http链接
            urls: source // 需要预览的图片http链接列表
        })
    },
    //提交
    to_submit: function (e) {
        var that = this;
        let full_name = that.data.full_name; //姓名
        let phone_number = that.data.phone_number; //电话
        let idCard_z = that.data.idCard_z; //身份证（正）
        let idCard_f = that.data.idCard_f; //身份证（反）
        let idCard = that.data.idCard; //身份证号码
        let household = that.data.household; //户口本

        if (full_name == '') {
            wx.showToast({
                title: '请填写委托人姓名',
                icon: 'none',
                mask: false,
            });
            return false;
        } else if (phone_number === '') {
            wx.showToast({
                title: '请填写委托人联系电话',
                icon: 'none',
                mask: false,
            });
            return false;
        } else if (!(/^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(phone_number))) {
            wx.showToast({
                title: '请输入正确的手机号码',
                icon: 'none',
                mask: true,
                duration: 1500
            });
            return
        } else if (idCard_z === '') {
            wx.showToast({
                title: '请上传身份证正面照',
                icon: 'none',
                mask: false,
            });
            return false;
        } else if (idCard_f === '') {
            wx.showToast({
                title: '请上传身份证背面照',
                icon: 'none',
                mask: false,
            });
            return false;
        } else if (idCard == '') {
            wx.showToast({
                title: '请填写身份证号',
                icon: 'none',
                duration: 1500,
                mask: true
            })
            return false;
        } else if (that._isIdCard(idCard) == false) {
            wx.showToast({
                title: '请输入正确的身份证号码',
                icon: 'none',
                mask: true,
                duration: 1500
            });
            return false;
        } else if (household === '') {
            wx.showToast({
                title: '请上传户口本图片',
                icon: 'none',
                mask: false,
            });
            return false;
        }
        this.setData({
            disabled: true
        })
        var modify = that.data.modify;
        var on_index = that.data.on_index; //当前修改数据的索引值
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2]; //上一个页面
        var client_list = prevPage.data.client_list;
        if (modify == false) { //【添加数据】
            var newData = {
                full_name: full_name, //姓名
                phone_number: phone_number, //电话
                idCard_z: idCard_z, //身份证（正）
                idCard_f: idCard_f, //身份证（反）
                idCard: idCard, //身份证号
                household: household, //户口本

            };
            client_list.push(newData); //实质是添加lists数组内容，使for循环多一次
            prevPage.setData({
                client_list: client_list,
                no_list: false
            })
        } else { //【修改数据】
            var newData = {
                full_name: full_name, //姓名
                phone_number: phone_number, //电话
                idCard_z: idCard_z, //身份证（正）
                idCard_f: idCard_f, //身份证（反）
                idCard: idCard, //身份证号
                household: household, //户口本
            };
            prevPage.setData({
                [`client_list[${on_index}]`]: newData
            })
        }
        wx.showToast({
            title: '上传中...',
            icon: 'loading',
            mask: true,
            duration: 1500,
            success(res) {
                setTimeout(() => { //上传成功后pages/material/pages/attest/index
                    wx.navigateBack({
                        delta: 0
                    })
                }, 1500)
            }
        });
    },
    //身份证验证
    _isIdCard: function (value) {
        let idCard = value;
        if (idCard.length == 15) {
            return this.__isValidityBrithBy15IdCard;
        } else if (idCard.length == 18) {
            let arrIdCard = idCard.split("");
            if (this.__isValidityBrithBy18IdCard(idCard) && this.__isTrueValidateCodeBy18IdCard(arrIdCard)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    },
    __isTrueValidateCodeBy18IdCard: function (arrIdCard) {
        let sum = 0;
        let Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1];
        let ValideCode = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2];
        if (arrIdCard[17].toLowerCase() == 'x') {
            arrIdCard[17] = 10;
        }
        for (let i = 0; i < 17; i++) {
            sum += Wi[i] * arrIdCard[i];
        }
        let valCodePosition = sum % 11;
        if (arrIdCard[17] == ValideCode[valCodePosition]) {
            return true;
        } else {
            return false;
        }
    },
    __isValidityBrithBy18IdCard: function (idCard18) {
        let year = idCard18.substring(6, 10);
        let month = idCard18.substring(10, 12);
        let day = idCard18.substring(12, 14);
        let temp_date = new Date(year, parseFloat(month) - 1, parseFloat(day));
        if (temp_date.getFullYear() != parseFloat(year) || temp_date.getMonth() != parseFloat(month) - 1 ||
            temp_date.getDate() !=
            parseFloat(day)) {
            return false;
        } else {
            return true;
        }
    },
    __isValidityBrithBy15IdCard: function (idCard15) {
        let year = idCard15.substring(6, 8);
        let month = idCard15.substring(8, 10);
        let day = idCard15.substring(10, 12);
        let temp_date = new Date(year, parseFloat(month) - 1, parseFloat(day));
        if (temp_date.getYear() != parseFloat(year) || temp_date.getMonth() != parseFloat(month) - 1 ||
            temp_date.getDate() !=
            parseFloat(day)) {
            return false;
        } else {
            return true;
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        var that = this;
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2]; //上一个页面
        var client_list = prevPage.data.client_list;
        console.log(client_list)
        if (typeof (options.index) != 'undefined') {
            wx.setNavigationBarTitle({
                title: '修改委托人信息'
            })
            that.setData({
                modify: true,
                on_index: options.index,
                full_name: client_list[options.index].full_name, //姓名
                phone_number: client_list[options.index].phone_number, //电话
                idCard_z: client_list[options.index].idCard_z, //身份证（正）
                idCard_f: client_list[options.index].idCard_f, //身份证（反）
                idCard: client_list[options.index].idCard, //身份证号
                household: client_list[options.index].household, //户口本
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    }
})